package com.hanxiaozhang.no10leetcode.backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 * 给一个可能有重复数字的集合，返回所有存在的组合
 * 例：
 * 输入: [1,1,2]
 * 输出: [ [1,1,2], [1,2,1], [2,1,1] ]
 *
 * todo
 *
 * @author hanxinghua
 * @create 2024/2/6
 * @since 1.0.0
 */
public class No47PermutationII {

    public static void main(String[] args) {


    }



    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return result;
        }
        Arrays.sort(nums);
        List<Integer> list = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        backTrack(nums, result, list, used);
        return result;
    }

    private void backTrack(int[] nums, List<List<Integer>> result, List<Integer> list, boolean[] used) {
        if (list.size() == nums.length) {
            result.add(new ArrayList<>(list));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (used[i] || (i > 0 && nums[i - 1] == nums[i] && !used[i - 1])) {
                continue;
            }
            used[i] = true;
            list.add(nums[i]);
            backTrack(nums, result, list, used);
            list.remove(list.size() - 1);
            used[i] = false;
        }
    }

}
